package threadLearn;

/**
 * 对象锁的第一种形式
 * 对象锁实例，代码块形式
 * @author 12609
 *
 */
public class SynchronizedCodeBlock implements Runnable{
	
	static SynchronizedCodeBlock instance = new SynchronizedCodeBlock();
	Object lock1 = new Object();
	Object lock2 = new Object();

	@Override
	public void run() {
		/**
		 * 也可以使用synchronized(this)
		 */
		synchronized (lock1) {
			System.out.println("lock1 开始 " + Thread.currentThread().getName());
			try {
				Thread.sleep(3000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			System.out.println("" + Thread.currentThread().getName() + " lock1运行结束");
		}
		
		synchronized (lock1) {
			System.out.println("lock2 开始 " + Thread.currentThread().getName());
			try {
				Thread.sleep(3000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			System.out.println("" + Thread.currentThread().getName() + " lock1运行结束");
		}
	}
	
	public static void main(String[] args) throws InterruptedException {
		Thread t1 = new Thread(instance);
		Thread t2 = new Thread(instance);
		t1.start();
		t2.start();
//		t1.join();//把指定的线程加入到当前线程，可以将两个交替执行的线程合并为顺序执行的线程。比如在线程B中调用了线程A的Join()方法，直到线程A执行完毕后，才会继续执行线程B。
//		t2.join();
		while(t1.isAlive() || t2.isAlive()) {
			//循环等待
		}
		System.out.println("finished...");
	}

}
